package org.standard;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.ImageProducer;
import java.awt.image.MemoryImageSource;
import java.awt.image.PixelGrabber;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.WeakHashMap;

public class Utility {
	final static private ClassLoader classLoader = Thread.currentThread()
			.getContextClassLoader();
	final static private Map cacheImages = new WeakHashMap(100);
	final static private MediaTracker mediaTracker = new MediaTracker(
			new Container());
	final static private Toolkit toolKit = Toolkit.getDefaultToolkit();

	final static public BufferedImage createImage(int i, int j, boolean flag) {
		if (flag) {
			return new BufferedImage(i, j, 2);
		} else {
			return new BufferedImage(i, j, 1);
		}

	}

	public final static InputStream getResource(final String fileName) {
		return new BufferedInputStream(classLoader
				.getResourceAsStream(fileName));
	}

	final static public Image loadImage(final String fileName) {
		String keyName = fileName.trim().toLowerCase();
		Image cacheImage = (Image) cacheImages.get(keyName);
		if (cacheImage == null) {
			InputStream in = new BufferedInputStream(classLoader
					.getResourceAsStream(fileName));
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			try {
				byte[] bytes = new byte[8192];
				int read;
				while ((read = in.read(bytes)) >= 0) {
					byteArrayOutputStream.write(bytes, 0, read);
				}
				byte[] arrayByte = byteArrayOutputStream.toByteArray();
				cacheImages.put(keyName, cacheImage = toolKit
						.createImage(arrayByte));
				mediaTracker.addImage(cacheImage, 0);
				mediaTracker.waitForID(0);
				waitImage(100, cacheImage);
			} catch (Exception e) {
				throw new RuntimeException(fileName + " not found!");
			} finally {
				try {
					if (byteArrayOutputStream != null) {
						byteArrayOutputStream.close();
						byteArrayOutputStream = null;
					}
					if (in != null) {
						in.close();
					}
				} catch (IOException e) {
				}
			}

		}
		if (cacheImage == null) {
			throw new RuntimeException(("File not found. ( " + fileName + " )")
					.intern());
		}
		return cacheImage;
	}
	private final static void waitImage(int delay, Image image) {
		try {
			for (int i = 0; i < delay; i++) {
				if (toolKit.prepareImage(image, -1, -1, null)) {
					return;
				}
				Thread.sleep(delay);
			}
		} catch (Exception e) {

		}
	}
}
